package com.mls.guardian.appst.chain.excutor;

import com.mls.guardian.appst.chain.TaskExecutor;
import com.mls.guardian.appst.chain.TaskInvoker;
import com.mls.guardian.appst.chain.TaskResult;
import com.mls.guardian.appst.chain.excutor.Upgrade.GitPullExcutor;
import com.mls.guardian.appst.shell.ShellScriptExecutorFuture;
import com.mls.guardian.common.GitUtil;
import com.mls.guardian.common.SvnUtil;
import com.mls.guardian.em.RevisionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengrenfang on 15/10/30.
 */
public class RevisionUpdateExcutor implements TaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(RevisionUpdateExcutor.class);

    @Override
    public TaskResult exec(TaskInvoker invoker) {
        String revisionAddress = invoker.getProject().getRevisionAddress();
        RevisionType revisionType = invoker.getProject().getRevisionType();
        String projectPath = invoker.getProject().getProjectPath();

        TaskResult result = null;
        try {
            log.info("----开始svn update----");
            List<String> list = new ArrayList<String>();

            switch (revisionType){
                case SVN:
                    String str = SvnUtil.getUpdateShellString(projectPath,revisionAddress);
                    list.add(str);
                case GIT:
                    String shellStr = GitUtil.getUpdateShellString(projectPath,revisionAddress);
                    list.add(shellStr);
            }
            list.add("exit");


            result = new ShellScriptExecutorFuture(list,5 * 60 * 1000L).execute();

            if(!result.isSuc()){
                System.out.println("result is " + result.getError());
                if(!isRealError(result.getError())){
                    result.setSuc(Boolean.TRUE);
                }
            }
        } catch (Exception e) {
            result = new TaskResult();
            result.setSuc(false);
            result.setError(e.getMessage());

            e.printStackTrace();
        } finally {
            log.info("----结束svn update[{}]----", result.isSuc());
        }

        if (result.isSuc() == true) {
            return invoker.invoke();
        }

        return result;
    }


    private boolean isRealError(String str){
        if(str.contains("Cloning into") || str.contains("Checking out files") || str.contains("From")){
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }
}
